//
//  CZLoginViewController.swift
//  sinaSwifWeiBo
//
//  Created by 张雪雪 on 16/2/27.
//  Copyright © 2016年 张雪雪. All rights reserved.
//

import UIKit
import AFNetworking

import SVProgressHUD

class CZLoginViewController: UIViewController , UIWebViewDelegate{

    //创建网页
    
    var webView: UIWebView?
    
    
    override func loadView() {
        
        
        //一定要注意创建实例
        webView = UIWebView()
        
        view = webView
        
        //设置代理对象
        webView?.delegate = self
        
        view = webView
        
        print(view)
 
    }
    
    
 
    override func viewDidLoad() {
        
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        

        view.backgroundColor = UIColor.whiteColor()
        
        
        setupNav()
        
        //设置请求URL
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(App_KEY)&redirect_uri=\(App_URL)&response_type=code")!
        
        //创建请求记得强制解包
        let request = NSURLRequest(URL: url)
        
        
        //加载请求
        
        webView?.loadRequest(request)
        
        
        
    }

    private func setupNav(){
    
    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "dismiss")
        
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "auto")
    
        }
    
   //MARK:--实现nav的按钮方法
    func dismiss (){
    
    dismissViewControllerAnimated(true) { () -> Void in
        
         print("返回成功")
        
        }
    
    }
    
    
    
    
   @objc  private func auto() {
    

    //      print("自动填充")
    
    //自己
        let js = "document.getElementById(\"userId\").value = \"1273892992@qq.com\";document.getElementById(\"passwd\").value = \"asdfg@5211314\";"
//    let js = "document.getElementById(\"userId\").value = \"snowkimi521@sina.com\";document.getElementById(\"passwd\").value = \"asdfg@5211314\";"
    
        //注入到web页面
        
        webView?.stringByEvaluatingJavaScriptFromString(js)
        
    
    }
    
}
 //把webView的代理方法写在这里
    
extension CZLoginViewController{
    
    
    func webViewDidStartLoad(webView: UIWebView) {
        /*
        1. show()就是一个默认的加载提示
        2. showErrorWithStatus("error")显示错误信息
        */
        
        SVProgressHUD.show()
        
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
//dismiss () 消息的方法
        SVProgressHUD.dismiss()
        
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
        SVProgressHUD.dismiss()
    }

            // 重点 是这个方法
        /*
        这个方法--只要我们加载网页的URL,都会走这个方法,默认返回 true
        
        */
        
     func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
            
            //        print("你好")
            //URL的绝对路径,可以将URL转换成String
            if let url = request.URL?.absoluteString {
                
                if url.hasPrefix(App_URL){
                    
                   // print(url)
                    
                    //let subString = url.componentsSeparatedByString("=")
                    
                    //                if subString.count > 0{
                    //
                    //                let code = subString.last
                    //
                    //                    print(code ?? 0)//=print(code !)
                    //
                    //                }
                    
                    if let code = request.URL?.query{
                        //print(code)
                        
                        //可以在截取
                        
                        let subCode = code.substringFromIndex("code=".endIndex)
                        
                        // print(subCode)
                    //let userViewModel =
                        
                CZUserViewModel().loadToken(subCode, success: {() -> () in
                            
                            //成功的回调
                        
                        print("成功")
                    /* 
                    处理方法
                    1.不能显示回回调页
                    2.授权成功之后应该返回首页
                    
                    */
                    /**
                    *  页面消失的时候,改变回调页
                    不建议改keyWindow,不建议这样做
                    
                    */
                    
                    NSNotificationCenter.defaultCenter().postNotificationName(kNotificaionChangeRootVC, object: nil)
                    
                        self.dismissViewControllerAnimated(true, completion: { () -> Void in
                            print("消失了")
                        })
                        
                        
                            }, failure: { () -> () in
                                
                                //失败的回调
                        
                          print("失败")
                        
                        
                        })
                       
                      //返回一个false的话,下边的RUL页面就不加载
                        return false
                        
                    }
                    
                }
                
            }
            
            return true
        }
    
}
//MARK: --通过code来换取Token
    extension CZLoginViewController {
}
//MARK:--通过Token来换取用户信息
extension CZLoginViewController{

}
    
    
    
    
    
    

    
  
    
    
    
    

